import json
import time
from typing import List

import pydantic
from sqlalchemy import delete, insert, select

from forward.api.admin.schemas.decorate import (
    DecorateTabbarOutSchema,
    DecorateTabbarStyleSchema,
    DecorateTabbarListSchema,
    DecorateTabbarSaveInSchema,
)
from forward.dependencies.database import db
from forward.model.tables.decorate import DecorateTabbarModel
from forward.utils.config import ConfigUtil
from forward.utils.tools import ToolsUtil
from forward.utils.urls import UrlUtil


class DecorateTabbarService:

    async def detail(self) -> DecorateTabbarOutSchema:
        tabbar_records = await db.fetch_all(
            select(DecorateTabbarModel)
            .select_from(DecorateTabbarModel)
            .order_by(DecorateTabbarModel.id.asc())
        )
        tabbar_list = [
            DecorateTabbarListSchema.model_validate(tabbar_record, from_attributes=True)
            for tabbar_record in tabbar_records
        ]

        tabbar_style = await ConfigUtil.get_val("tabbar", "style", "{}")
        if tabbar_style:
            style = DecorateTabbarStyleSchema.model_validate(
                ToolsUtil.json_to_map(tabbar_style)
            )
        else:
            style = DecorateTabbarStyleSchema(defaultColor="", selectedColor="")
        return DecorateTabbarOutSchema(style=style, list=tabbar_list)

    @db.transaction()
    async def save(self, save_in: DecorateTabbarSaveInSchema):
        await db.execute(delete(DecorateTabbarModel).where(DecorateTabbarModel.id > 0))

        tabbar_list = save_in.list

        for obj in tabbar_list:
            save_dict = {
                "name": obj.name,
                "selected": await UrlUtil.to_relative_url(obj.selected),
                "unselected": await UrlUtil.to_relative_url(obj.unselected),
                "link": obj.link,
            }
            await db.execute(insert(DecorateTabbarModel).values(**save_dict))
        tabbar_style = save_in.style
        if tabbar_style:
            await ConfigUtil.set(
                "tabbar", "style", json.dumps(tabbar_style.model_dump())
            )

    @classmethod
    async def instance(cls):
        """实例化"""
        return cls()
